//
//  CityCoordinator.swift
//  CitySearch
//
//  Created by guotonglin on 2020/6/3.
//  Copyright © 2020 guotonglin. All rights reserved.
//

import Foundation
import UIKit
import RxCocoa
import RxSwift

class AirportCoordinator: BaseCoordinator {

    
    private let models: Set<AirportModel>

//    private let navigationController: UINavigationController
//    init(models: Set<AirportModel>, navigationController: UINavigationController) {
//        self.models = models
//        self.navigationController = navigationController
//    }
//
    private let router: Routing
    
    private let bag = DisposeBag()
    
    init(models: Set<AirportModel>, router: Routing) {
        self.models = models
        self.router = router
    }

    override func start() {
        let vc = AirportViewController.instantiate()
        
        let locationService = LocationService.shared
        
        vc.viewModelBuilder = { [models, bag, locationService] in
            var viewModel = AirportsViewModel(input: $0, dependencies: (title: models.first?.city ?? "",
                                                        models: models,
                                                        currentLocation: locationService.currentLocation))
            
            viewModel.router
                .citySelected
                .map ( {[weak self] airportModel in
                    self?.showAirportDetail(model: airportModel)
                })
                .drive()
                .disposed(by: bag)
            
            return viewModel
        }
        self.router.push(vc, isAnimated: true, onNavigationBack: isCompleted)
    }
}

extension AirportCoordinator {
    
    func showAirportDetail(model: AirportModel) {
        let airportDetailCoordinator = AirportDetailsCoordinator(model: model, router: self.router)
        airportDetailCoordinator.isCompleted = { [weak self, weak airportDetailCoordinator] in
            guard let `self` = self, let airportDetailCoordinator = airportDetailCoordinator else {
                return
            }
            self.remove(coordinator: airportDetailCoordinator)
        }
        airportDetailCoordinator.start()
        self.add(coordinator: airportDetailCoordinator)
    }
    
}
